//
//  AddDocAdviceVC.m
//  Doctor
//
//  Created by 阳光 on 16/9/7.
//  Copyright © 2016年 阳光. All rights reserved.
//  添加医嘱界面

#import "AddDocAdviceVC.h"
#import "VisitPatientInfoVC.h"

static NSString *tableViewCellIdentifier=@"TableViewCellIdentifier";

@interface AddDocAdviceVC ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,strong)UIScrollView *scrollView;

@property(nonatomic,strong)UIView *selectTimeView;

@property(nonatomic,strong)UIView *mainView;

@property(nonatomic,strong)NSMutableArray *dataArr;

@end



@implementation AddDocAdviceVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = NSLocalizedString(@"Add advice", nil);//@"添加医嘱";
    
    [self initNavBarBtnItem];
    
    [self initScrollView];
    
    [self setView];
    
    [self createTableView];
    
    [self initBottomView];
    
}

-(void)setView
{
    _dataArray=[NSMutableArray array];
    
    _selectViewTag = 0;
    
    _array1=@[@"一支",@"两支",@"三支",@"四支"];//一支，两支，三支，四支
    _array2=@[@"0.05mg",@"01.mg",@"0.375mg",@"1.25mg",@"1.875mg",@"3.75mg"];
    _array3= @[@"8.3iu",@"25iu",@"37.5iu",@"50iu",@"75iu",@"100iu",@"125iu",@"150iu",@"187.5iu",@"200iu",@"225iu",@"300iu",@"325iu",@"350iu",@"375iu",@"400iu"];
    
    // _array5 =@[@"打针",@"吃药",@"B超",@"验血",@"取卵",@"取精",@"移植"];
    _array5 = @[NSLocalizedString(@"Injection", nil) ,NSLocalizedString(@"Take Medicine", nil) ,NSLocalizedString(@"B Ultrasound", nil) ,NSLocalizedString(@"Blood Test", nil) ,NSLocalizedString(@"Ovum Pick", nil) ,NSLocalizedString(@"Sperm Pick", nil) ,NSLocalizedString(@"Transfer", nil)];
    
    //_array6=@[@"思则凯",@"乐芮",@"爱斯妥",@"雪诺酮",@"黄体酮注射剂",@"达菲林",@"达必佳",@"天兴",@"果纳芬",@"丽申宝",@"普丽康",@"福特蒙",@"贺美奇",@"克罗米芬",@"来曲唑",@"补佳乐",@"安琪坦",@"达芙通"];
    _array6=@[NSLocalizedString(@"Cetrotide", nil) ,NSLocalizedString(@"Luveris", nil) ,NSLocalizedString(@"EstradiolGel", nil) ,NSLocalizedString(@"Crinone", nil) ,@"黄体酮注射剂" ,NSLocalizedString(@"Diphereline", nil) ,NSLocalizedString(@"Decapepthl", nil) ,@"天兴" ,NSLocalizedString(@"Gonal-f", nil) ,@"丽申宝" ,NSLocalizedString(@"Puregon", nil) ,NSLocalizedString(@"Fostimen", nil) ,NSLocalizedString(@"Menopur", nil) ,NSLocalizedString(@"Clomiphene", nil) ,NSLocalizedString(@"Letrozole", nil) ,NSLocalizedString(@"EstradiolValerate Tablets", nil) ,NSLocalizedString(@"Progesterone Capsules", nil) ,NSLocalizedString(@"Dydrogesterone Tablets", nil)];
    
    //_doseArray=@[@"1支",@"2支",@"3支",@"4支",@"4分之一片",@"2分之一片",@"1片",@"2片",@"3片",@"4片",@"0.05mg",@"01.mg",@"0.375mg",@"1.25mg",@"1.875mg",@"3.75mg",@"8.3iu",@"25iu",@"37.5iu",@"50iu",@"75iu",@"100iu",@"125iu",@"150iu",@"187.5iu",@"200iu",@"225iu",@"300iu",@"325iu",@"350iu",@"375iu",@"400iu"];
    _doseArray=@[NSLocalizedString(@"1 dose", nil) ,NSLocalizedString(@"2 dose", nil) ,NSLocalizedString(@"3 dose", nil) ,NSLocalizedString(@"4 dose", nil) ,NSLocalizedString(@"1/4 tablet", nil) ,NSLocalizedString(@"1/2 tablet", nil) ,NSLocalizedString(@"1 tablet", nil) ,NSLocalizedString(@"2 tablet", nil) ,NSLocalizedString(@"3 tablet", nil) ,NSLocalizedString(@"4 tablet", nil) ,@"0.05mg",@"01.mg",@"0.375mg",@"1.25mg",@"1.875mg",@"3.75mg",@"8.3iu",@"25iu",@"37.5iu",@"50iu",@"75iu",@"100iu",@"125iu",@"150iu",@"187.5iu",@"200iu",@"225iu",@"300iu",@"325iu",@"350iu",@"375iu",@"400iu"];
    
}

-(void)createTableView
{
    // 创建tableView
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0,APPH,APPW,APPH-64-150-84) style:UITableViewStylePlain];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.showsVerticalScrollIndicator=NO;
    _tableView.separatorColor=ClearColor;
    _tableView.hidden=YES;
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:tableViewCellIdentifier];
    [_scrollView addSubview:_tableView];
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:tableViewCellIdentifier];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.textLabel.text=_dataArray[indexPath.row];
    cell.textLabel.textColor=Color000000;
    cell.textLabel.textAlignment=NSTextAlignmentCenter;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kmargin*4;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIButton *actionBtn=(UIButton *)[self.view viewWithTag:200+_selectViewTag-1];
    UIButton *imageBtn=(UIButton *)[self.view viewWithTag:300+_selectViewTag-1];
    
    actionBtn.selected=NO;
    imageBtn.selected=NO;
    
    UITableViewCell *cell=(UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    [actionBtn setTitle:cell.textLabel.text forState:0];
    
    [UIView animateWithDuration:0.1 animations:^{
        _tableView.frame=CGRectMake(0,APPH,APPW,APPH-64-_tableViewY);
    }];
    _tableView.hidden=YES;
    
    NSString *injection = NSLocalizedString(@"Injection", nil);//@"打针";
    NSString *takeMedical = NSLocalizedString(@"Take Medicine", nil);//@"吃药";
    
    UIView *view1=(UIView *)[self.view viewWithTag:401];
    UIView *view2=(UIView *)[self.view viewWithTag:402];
    if (_selectViewTag==1)
    {
        if ([cell.textLabel.text isEqualToString:injection]||[cell.textLabel.text isEqualToString:takeMedical])
        {
            [self selectMedical];
        }
        else
        {
            view1.hidden=YES;
            view2.hidden=YES;
        }
    }
    
    if (_selectViewTag==2)
    {
        [self selectDose];
    }
}


-(void)selectMedical
{
    // 选择药品
    UIView *view=(UIView *)[self.view viewWithTag:401];
    view.hidden=NO;
}


-(void)selectDose
{
    // 选择剂量
    UIView *view=(UIView *)[self.view viewWithTag:402];
    view.hidden=NO;
}

-(void)initScrollView
{
    _scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0,0,APPW,APPH-64)];
    _scrollView.backgroundColor=MAIN_BACK_COLOR;
    _scrollView.showsVerticalScrollIndicator=NO;
    [self.view addSubview:_scrollView];
    
    _selectTimeView=[self setSelectTimeView];
    setViewCoord_Y(_selectTimeView,0);
    [_scrollView addSubview:_selectTimeView];
    
    _mainView=[self setMainView];
    setViewCoord_Y(_mainView,_selectTimeView.frame.origin.y+_selectTimeView.frame.size.height);
    [_scrollView addSubview:_mainView];
    
    _scrollView.contentSize=CGSizeMake(APPW,CGRectGetMaxY(self.mainView.frame)+kmargin);
    
}


#define cellH   50
-(UIView *)setMainView
{
    UIView *mainView=[[UIView alloc]initWithFrame:CGRectMake(0,0,APPW,0)];
    mainView.backgroundColor=MAIN_BACK_COLOR;
    setViewHeight_Add(mainView,1);

    NSArray *array = @[NSLocalizedString(@"Select item", nil),NSLocalizedString(@"Select drug", nil),NSLocalizedString(@"Select dosage", nil)];//@[@"选择项目",@"选择药品",@"选择计量"]

    for (int i=0;i<3;i++)
    {
        UIView *actionView=[[UIView alloc]initWithFrame:CGRectMake(0,mainView.frame.size.height+(cellH)*i,APPW,cellH-1)];
        actionView.backgroundColor=WhiteColor;
        actionView.tag=400+i;
        [mainView addSubview:actionView];
        
        UIButton *actionBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        actionBtn.frame=CGRectMake(kmargin,0,APPW-kmargin,cellH-1);
        [actionBtn setTitleColor:Color000000 forState:0];
        actionBtn.selected=NO;
        actionBtn.titleLabel.font=Font_Number(16);
        actionBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
        [actionBtn setTitle:array[i] forState:0];
        actionBtn.tag=200+i;
        [actionBtn addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
        [actionView addSubview:actionBtn];
        
        UIImageView *arrow=[UIImageView new];
        arrow.frame=CGRectMake(APPW-kmargin*4,(cellH-kmargin)/2,kmargin*3/2,kmargin);
        arrow.image=[UIImage imageNamed:@"arrow_down"];
        [actionBtn addSubview:arrow];
        arrow.userInteractionEnabled=NO;
        
        if (i==0)
        {
            actionView.hidden=NO;
        }
        else
        {
            actionView.hidden=YES;
        }
    }
    setViewHeight_Add(mainView,kmargin+cellH*3);
    
    return mainView;
    
}

-(void)selectAction:(UIButton *)sender
{
    [_dataArray removeAllObjects];
    
    UIView *view;
    if (sender.tag<300)
    {
        view=(UIView *)[self.view viewWithTag:sender.tag+200];
    }
    else
    {
        view=(UIView *)[self.view viewWithTag:sender.tag+100];
    }
    
    if (view.tag ==400)
    {
        _selectViewTag=1;
        _dataArray=[NSMutableArray arrayWithArray:_array5];
    }
    else if(view.tag==401)
    {
        _selectViewTag=2;
        _dataArray=[NSMutableArray arrayWithArray:_array6];
    }
    else if(view.tag==402)
    {
        _selectViewTag=3;
        _dataArray=[NSMutableArray arrayWithArray:_doseArray];
    }
    
    sender.selected=!sender.selected;
    
    if (_selectViewTag==1)
    {
        _tableViewY=150;
    }
    else if (_selectViewTag==2)
    {
        _tableViewY=200;
    }
    else
    {
        _tableViewY=250;
    }
    
    if (sender.selected)
    {
        _tableView.hidden=NO;
        [UIView animateWithDuration:0.1 animations:^{
            _tableView.frame=CGRectMake(0,_tableViewY,APPW,APPH-64-_tableViewY-84);
        }];
    }
    else
    {
        [UIView animateWithDuration:0.1 animations:^{
            _tableView.frame=CGRectMake(0,APPH,APPW,0);
        }];
    }
    
    for(UIButton *but in view.subviews)
    {
        if (sender.selected)
        {
            but.selected=YES;
        }
        else
        {
            but.selected=NO;
        }
    }
    
    [_tableView reloadData];
}


-(UIView *)setSelectTimeView
{
    UIView *selectTimeView=[[UIView alloc]initWithFrame:CGRectMake(0,0,APPW,0)];
    selectTimeView.backgroundColor=WhiteColor;
    
    UIView *topLine=[[UIView alloc]initWithFrame:CGRectMake(0,0,APPW,1)];
    [selectTimeView addSubview:topLine];
    topLine.backgroundColor=MAIN_BACK_COLOR;
    
    setViewHeight_Add(selectTimeView,kmargin+1);
    
    UIView *setTimeView=[[UIView alloc]initWithFrame:CGRectMake(0,selectTimeView.frame.size.height,APPW,70)];
    [selectTimeView addSubview:setTimeView];
    
    
    NSArray *array = @[NSLocalizedString(@"Add Start Time", nil) ,NSLocalizedString(@"Add End Time", nil)];//@[@"开始时间",@"结束时间"]
    for (int i=0;i<2;i++) {
        UILabel *label=[setTimeView getLabelWithText:array[i] font:Font_Number(15) textColor:Color666666 textAlignment:NSTextAlignmentCenter lineBreakMode:NSLineBreakByCharWrapping numberOfLines:1];
        label.frame=CGRectMake(kmargin+((APPW-kmargin*4)/2+kmargin*3)*i,5,(APPW-kmargin*4)/2,30);
        [setTimeView addSubview:label];
        label.userInteractionEnabled=YES;
        
 
        UIButton *time=[UIButton buttonWithType:UIButtonTypeCustom];
        time.frame = CGRectMake(kmargin+((APPW-kmargin*4)/2+kmargin*3)*i,35,(APPW-kmargin*4)/2,30);
        [time setBackgroundColor:ClearColor];
        time.titleLabel.font=Font_Number(15);
        time.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
        [time setTitleColor:Color000000 forState:0];
        time.tag=100+i;
        if (i==0)
        {
            [time setTitle:NSLocalizedString(@"Select start time", nil) forState:0];//@"请选择开始时间"
        }
        else
        {
            [time setTitle:NSLocalizedString(@"Select end time", nil) forState:0];//@"请选择结束时间"
        }
        
        [time addTarget:self action:@selector(selectTime:) forControlEvents:UIControlEventTouchUpInside];
        [setTimeView addSubview:time];
    }
    
    UIImageView *arrowsImageView=[[UIImageView alloc]initWithFrame:CGRectMake(kmargin+(APPW-kmargin*4)/2,25,kmargin*2,kmargin*2)];
    arrowsImageView.image=[UIImage imageNamed:@"cell_arrow"];
    [setTimeView addSubview:arrowsImageView];
    
    setViewHeight_Add(selectTimeView,70);
    
    UIView *midLine=[[UIView alloc]initWithFrame:CGRectMake(0,selectTimeView.frame.size.height,APPW,1)];
    midLine.backgroundColor=MAIN_BACK_COLOR;
    [selectTimeView addSubview:midLine];
    
    setViewHeight_Add(selectTimeView,1);
    
    return selectTimeView;
    
}


-(void)selectTime:(UIButton *)sender
{
    //100 101
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
    dateFormatter.dateFormat=@"yyyy-MM-dd HH:mm";
    
    UIDatePicker *datePicker=[[UIDatePicker alloc]initWithFrame:CGRectMake(0,0,APPW,216)];
    datePicker.datePickerMode=UIDatePickerModeDateAndTime;
    if (sender.tag == 101)
    {
        // 结束时间
        UIButton *beginBtn = (UIButton *)[self.view viewWithTag:100];
        NSString *beginStr = beginBtn.titleLabel.text;
        if ([beginStr isEqualToString:NSLocalizedString(@"Select start time", nil)])
        {
            [self.view makeToast:NSLocalizedString(@"Please select start time", nil) duration:1.0 position:CSToastPositionCenter];
            return;
        }
        else
        {
            NSDate *endminiDate=[dateFormatter dateFromString:beginStr];
            datePicker.minimumDate=endminiDate;
        }
    }
    else
    {
        // 开始时间
        datePicker.minimumDate=[NSDate date];
    }
    
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"\n\n\n\n\n\n\n\n\n\n" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert.view addSubview:datePicker];
    

    UIAlertAction *cancel=[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel handler:nil];//@"取消"@"确定"
    UIAlertAction *ok=[UIAlertAction actionWithTitle:NSLocalizedString(@"Sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
        {
        NSString *dateStr=[dateFormatter stringFromDate:datePicker.date];
        [sender setTitle:dateStr forState:UIControlStateNormal];
    }];
    [alert addAction:cancel];
    [alert addAction:ok];
    [self presentViewController:alert animated:NO completion:nil];
    
}

-(void)submitBtnEvent
{
    // 开始时间
    UIButton *beginTimeBtn=(UIButton *)[self.view viewWithTag:100];
    // 结束时间
    UIButton *endTimeBtn=(UIButton *)[self.view viewWithTag:101];
    
    // 当没有选择开始时间时
    if ([beginTimeBtn.titleLabel.text isEqualToString:NSLocalizedString(@"Select start time", nil)])
    {
        [self.view makeToast:NSLocalizedString(@"Please select start time", nil) duration:1.0 position:CSToastPositionCenter];
        return;
    }
    
    // 当没有选择结束时间时
    if ([endTimeBtn.titleLabel.text isEqualToString:NSLocalizedString(@"Select end time", nil)])
    {
        [self.view makeToast:NSLocalizedString(@"Please select end time", nil) duration:1.0 position:CSToastPositionCenter];
        return;
    }
    
    // 如果开始时间必须小于结束时间,否则重新选择时间
    NSComparisonResult result=[beginTimeBtn.titleLabel.text compare:endTimeBtn.titleLabel.text];
    if (result==NSOrderedDescending)
    {
        [self.view makeToast:NSLocalizedString(@"End Time not less than start time", nil) duration:1.0 position:CSToastPositionCenter];
    }
    else if (result==NSOrderedSame)
    {
        [self.view makeToast:NSLocalizedString(@"End Time do not match start time", nil) duration:1.0 position:CSToastPositionCenter];
    }
    
    // 选择项目
    UIButton *selectItemBtn=(UIButton *)[self.view viewWithTag:200];
    // 选择药品
    UIButton *selectMedicalBtn=(UIButton *)[self.view viewWithTag:201];
    // 选择剂量
    UIButton *selectDoseBtn=(UIButton *)[self.view viewWithTag:202];
    
    NSString *itemStr=selectItemBtn.titleLabel.text;
    NSString *medicalStr=selectMedicalBtn.titleLabel.text;
    NSString *doseStr=selectDoseBtn.titleLabel.text;
    
    NSString *injection = NSLocalizedString(@"Injection", nil);//@"打针";
    NSString *takeMedical = NSLocalizedString(@"Take Medicine", nil);//@"吃药";
    
    // 当没有选择项目时
    if ([itemStr isEqualToString:NSLocalizedString(@"Select item", nil)])
    {
        [self.view makeToast:NSLocalizedString(@"Please select item", nil) duration:1.0 position:CSToastPositionCenter];//@"请选择项目"
    }
    // 当选择打针吃药时
    else if ([itemStr isEqualToString:injection]||[itemStr isEqualToString:takeMedical])
    {

        if ([medicalStr isEqualToString:NSLocalizedString(@"Select drug", nil)])
        {
            [self.view makeToast:NSLocalizedString(@"Please select drug", nil) duration:1.0 position:CSToastPositionCenter];//@"请选择药品"
        }

        else
        {
            if ([doseStr isEqualToString:NSLocalizedString(@"Select dosage", nil)])
            {
                [self.view makeToast:NSLocalizedString(@"Please select dosage", nil) duration:1.0 position:CSToastPositionCenter];//@"请选择计量"
            }
            else
            {
                // 如果单位不是mg或iu
                if (![_array2 containsObject:doseStr]||[_array3 containsObject:doseStr]) {
                    doseStr = [Util changNameToHowMuchCode:doseStr];
                }
                
                NSDictionary *dic=@{
                                    @"user_id":_patientID,
                                    @"doctor_id":[Util getUserDefaultObjectForKey:@"id"],
                                    @"start_time":beginTimeBtn.titleLabel.text,
                                    @"end_time":endTimeBtn.titleLabel.text,
                                    @"type_name":[Util changNameToCode:itemStr],
                                    @"drug":[Util changNameToDrugCode:medicalStr],
                                    @"dose":doseStr
                                    };
                
                __weak typeof(self) weakSelf=self;
                [QBRequest AddDoctorAdviceWithDic:dic Success:^(id res)
                 {
                     [self.view makeToast:res[@"message"] duration:1.0 position:CSToastPositionCenter];
                     
                     dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(1.0*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                         
                         // 跳转到患者病例详情的医嘱中
                         VisitPatientInfoVC *visitPatientInfoVC=[VisitPatientInfoVC new];
                         visitPatientInfoVC.patientID=_patientID;
                         visitPatientInfoVC.typeStr=@"addDocAdvice";
                         visitPatientInfoVC.visitDocListModel=_visitDocListModel;
                         [weakSelf.navigationController pushViewController:visitPatientInfoVC animated:NO];
                         
                     });
                     
                 } failure:^(NSString *error)
                 {
                     [self.view makeToast:error duration:1.0 position:CSToastPositionCenter];
                 }];
            }
            
        }
    }
}



-(void)initBottomView
{
    // 提交
    UIButton *submitBtn=[UIButton new];
    [self.view addSubview:submitBtn];
    ViewBorderRadius(submitBtn,kmargin/2,2,ClearColor);
    submitBtn.backgroundColor=Main_Color;
    submitBtn.titleLabel.font=Font_Number(16);
    [submitBtn setTitle:NSLocalizedString(@"Submit", nil) forState:0];//@"提交"
    [submitBtn setTitleColor:WhiteColor forState:0];
    [submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-kmargin*2);
        make.size.mas_equalTo(CGSizeMake(APPW-kmargin*4,44));
        make.left.mas_equalTo(kmargin*2);
    }];
    [submitBtn addTarget:self action:@selector(submitBtnEvent) forControlEvents:UIControlEventTouchUpInside];
}

-(void)initNavBarBtnItem
{
    self.navigationItem.leftBarButtonItem=[UIBarButtonItem initWithNormalImage:@"back_gray" target:self action:@selector(backItemEvent)];
}

-(void)backItemEvent
{
    [self.navigationController popViewControllerAnimated:NO];
}


@end



